package com.example.springbootrbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootrbac.entity.UserEntity;
import com.example.springbootrbac.repository.UserRepository;
import com.example.springbootrbac.service.UserService;
import org.apache.ibatis.annotations.Insert;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl implements UserService {
    @Resource(name = "userRepository")
    UserRepository userRepository;
    @Resource(name = "bCryptPasswordEncoder")
    private PasswordEncoder passwordEncoder;

    @Override
    public String login(HttpServletRequest request, String username, String password) {

        UserEntity user = userRepository.selectOne(
                new QueryWrapper<UserEntity>()
                        .select("id","username", "password","identity","status")
                        .eq("username", username)
        );
        if (!ObjectUtils.isEmpty(user)) {
            if (user.getPassword().equals(password)) {
                HttpSession session =request.getSession() ;
                session.setAttribute("user",user);
                System.out.println(session.getAttribute("user"));
                session.setMaxInactiveInterval(10*60);//以秒为单位，即在没有活动10分钟后，session将失效
                return "token:欢迎" + username + "到来♪";
            }
        }
        return null;
    }

    @Override
    public String registered(String username, String password) {
        UserEntity user = userRepository.selectOne(      //排查用户名是否已经被注册
                new QueryWrapper<UserEntity>()
                        .select("username","password")
                        .eq("username",username)
        );
        if(ObjectUtils.isEmpty(user)){                     //结果为空，可以注册
            UserEntity userEntity = new UserEntity();
            userEntity.setUsername(username);
            userEntity.setPassword(passwordEncoder.encode(password));   //密码转码加密
            userEntity.setIdentity("user");
            userEntity.setStatus("normal");
            userRepository.insert(userEntity);
            UserEntity user_role = userRepository.selectOne(     //获取id并注册成一般用户
                    new QueryWrapper<UserEntity>()
                            .select("id")
                            .eq("username",username)
            );
            userRepository.addUserToRole(user_role.getId());
            return "token:Login_ok";
        }
        return null;
    }

}
